package com.example.a22310.myapplication.Fragment;


import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a22310.myapplication.Fragment.Club.Detail.FragmentDistance;
import com.example.a22310.myapplication.Fragment.Club.Detail.FragmentPopularity;
import com.example.a22310.myapplication.R;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * A simple {@link Fragment} subclass.
 */

public class ClubFragment extends Fragment implements View.OnClickListener{
    View view;
    private Fragment mTab01;
    private Fragment mTab02;
    private LinearLayout tab1,tab2;
    private TextView tv01,tv02;
    private ImageView img1,img2;



    SimpleDraweeView[] simpleDraweeViews;

    int currentItem;
    private ScheduledExecutorService executor;
    ViewPager viewPager;



    String[] imageUris = {
            "https://pic4.zhimg.com/03b2d57be62b30f158f48f388c8f3f33_b.png",
            "https://pic1.zhimg.com/4373a4f045e5e9ae16ebd6a624bf6228_b.png",
            "https://pic2.zhimg.com/0364e17a1561f48793993d8bf1cdc785_b.png",
            "https://pic2.zhimg.com/55fa74ff3eba164ed1db2037df1a8311_b.png",
            "https://pic4.zhimg.com/5dc30569c06e7c6266c9809f6eb80a7b_b.jpg"
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_club, container, false);
        int size = initSize();
        initTextViews(size);
        initViewPager();
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initEvent();
        setSelect(0);
    }
    public ClubFragment() {
        // Required empty public constructor
    }


    private void initView()
    {
        tab1 = (LinearLayout)view.findViewById(R.id.tab_popularity);
        tab2 = (LinearLayout)view.findViewById(R.id.tab_distance);
        tv01 = (TextView)view.findViewById(R.id.tv_left);
        tv02 = (TextView)view.findViewById(R.id.tv_right);
        img1 =(ImageView)view.findViewById(R.id.popularity);
        img2 =(ImageView)view.findViewById(R.id.distance);

    }
    private void initEvent()
    {
        tab1.setOnClickListener(this);
        tab2.setOnClickListener(this);
    }


    private void setSelect(int i)
    {
        FragmentManager fm =  getChildFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideFragment(transaction);

        switch (i) {

            case 0:
                if (mTab01 == null) {
                    mTab01 = new FragmentPopularity();
                    transaction.add(R.id.id_content, mTab01);
                } else {
                    transaction.show(mTab01);
                }
                tv01.setTextColor(this.getResources().getColor(R.color.white));
                img1.setImageResource(R.drawable.ic_popularity_impress);
                tab1.setBackgroundColor(this.getResources().getColor(R.color.green));

                //tv1.setBackgroundColor(Color.BLUE);
                break;
            case 1:
                if (mTab02 == null) {
                    mTab02 = new FragmentDistance();
                    transaction.add(R.id.id_content, mTab02);
                } else {
                    transaction.show(mTab02);

                }
                tv02.setTextColor(this.getResources().getColor(R.color.white));
                img2.setImageResource(R.drawable.ic_distance_impress);
                tab2.setBackgroundColor(this.getResources().getColor(R.color.green));
                break;

            default:
                break;
        }
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction)
    {
        if (mTab01 != null)
        {
            transaction.hide(mTab01);
        }
        if (mTab02 != null)
        {
            transaction.hide(mTab02);
        }
    }

    @Override
    public void onClick(View v)
    {
        resetImgs();
        switch (v.getId()) {
            case R.id.tab_popularity:
                setSelect(0);
                break;
            case R.id.tab_distance:
                setSelect(1);
                break;
            default:
                break;
        }
    }



    private void resetImgs()
    {


        img1.setImageResource(R.drawable.ic_popularity);
        img2.setImageResource(R.drawable.ic_distance);
        tab1.setBackgroundColor(this.getResources().getColor(R.color.colorDeepBlue));
        tab2.setBackgroundColor(this.getResources().getColor(R.color.colorDeepBlue));

        // tab1.setBackgroundColor(getActivity().getColor(R.color.green));


        tv01.setTextColor(this.getResources().getColor(R.color.green));
        tv02.setTextColor(this.getResources().getColor(R.color.green));


    }


    /*   轮播图*/

    private void init(){
        Fresco.initialize(getActivity());
    }

    @Override
    public void onResume() {
        super.onResume();

        startAutoScroll(); // activity激活时候自动播放
    }

    @Override
    public void onPause() {
        super.onPause();

        stopAutoScroll(); // activity暂停时候停止自动播放
    }

    private void startAutoScroll() {
        stopAutoScroll();

        executor = Executors.newSingleThreadScheduledExecutor();
        Runnable command = new Runnable() {
            @Override
            public void run() {
                selectNextItem();
            }

            private void selectNextItem() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        viewPager.setCurrentItem(++currentItem);
                    }
                });
            }
        };
        int delay = 2;
        int period = 2;
        TimeUnit timeUnit = TimeUnit.SECONDS;
        executor.scheduleAtFixedRate(command, delay, period, timeUnit);
    }

    private void stopAutoScroll() {
        if (executor != null) {
            executor.shutdownNow();
        }
    }



    private void initViewPager() {
        viewPager = (ViewPager) view.findViewById(R.id.viewPage);

        viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return Integer.MAX_VALUE; // 取一个大数字
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {

                SimpleDraweeView t = simpleDraweeViews[position % simpleDraweeViews.length];
                container.addView(t);

                Uri uri = Uri.parse(imageUris[position % simpleDraweeViews.length]);
                t.setImageURI(uri);

                return t;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {

                container.removeView((View) object);
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentItem = position;

                startAutoScroll(); // 手动切换完成后恢复自动播放
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        currentItem = imageUris.length * 1000000; // 取一个中间的大数字, 防止接近边界
        viewPager.setCurrentItem(currentItem);
    }

    private void initTextViews(int size) {
        SimpleDraweeView[] tvs = new SimpleDraweeView[size];
        init();
        for (int i = 0; i < tvs.length; i++) {
            tvs[i] = new SimpleDraweeView(getActivity());
            tvs[i].getHierarchy().setPlaceholderImage(R.mipmap.ic_launcher);

            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            tvs[i].setLayoutParams(layoutParams);
            simpleDraweeViews = tvs;
        }
    }

    private int initSize() {
        int size;
        if (imageUris.length > 3) {
            size = imageUris.length;
        } else {
            size = imageUris.length * 2; // 小于3个时候, 需要扩大一倍, 防止出错
        }
        return size;
    }



}
